package com.qingcloud.adminbackend.controller;


import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.equipment.StationGroupEquipmentBO;
import com.qingcloud.adminbackend.entity.equipment.SysEquipmentDTO;
import com.qingcloud.adminbackend.entity.stationgroup.*;
import com.qingcloud.adminbackend.entity.stationgroup.*;
import com.qingcloud.adminbackend.service.ISysStationGroupService;
import com.qingcloud.adminbackend.utils.CookieUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备组 前端控制器
 * </p>
 *
 * @author luozehua
 * @since 2018-11-15
 */
@Api(value = "设备组管理接口", description = "设备组管理接口")
@RestController
@RequestMapping("/station-group")
public class SysStationGroupController {

    @Resource
    private ISysStationGroupService sysStationGroupService;

    /**
     * 设备组分页查询
     *
     * @param sysStationGroup
     * @return
     */
    @ApiOperation(value = "设备组分页查询", notes = "设备组分页查询")
    @PostMapping(value = "/findStationGroupPage")
    public AjaxResult findStationGroupPage(@RequestBody SysStationGroupBO sysStationGroup, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        boolean isAdmin = CookieUtil.isAdmin(request);
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findStationGroupPage(sysStationGroup, userId, isAdmin));
    }


    /*
       {
          "description": "罗泽华测试设备组",
          "eqs": [
            {
              "equipmentId": "80021",
              "stationId": "80021"
            },
        {
              "equipmentId": "sb-20180706001",
              "stationId": "sb-20180706001"
            },
        {
              "equipmentId": "8000000",
              "stationId": "8000000"
            },
          ],
          "name": "罗泽华测试设备组",
          "orgId": "0ab6e734868e4a07a644499fda6cb67f"
        }
     */
    @ApiOperation(value = "新建设备组", notes = "新建设备组")
    @PostMapping(value = "/addStationGroup")
    public AjaxResult addStationGroup(@RequestBody StationgroupAddParam addParam, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        Boolean save = sysStationGroupService.addStationGroup(addParam, userId);
        if (save) {
            return new AjaxResult(WamingConstant.SUCCESS, "", "添加成功");
        } else {
            return new AjaxResult(WamingConstant.FAILURE, "添加失败", "添加失败");
        }
    }

    @ApiOperation(value = "修改设备组", notes = "修改设备组")
    @PostMapping(value = "/updateStationGroup")
    public AjaxResult updateStationGroup(@RequestBody StationgroupAddParam addParam, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        sysStationGroupService.updateStationGroup(addParam, userId);
        //分支机构的设备是否还有授权检查
        sysStationGroupService.checkEquipmentAuth();
        return new AjaxResult(WamingConstant.SUCCESS, "", "修改成功");
    }

    @ApiOperation(value = "删除设备组", notes = "删除设备组")
    @PostMapping(value = "/deleteStationGroup")
    public AjaxResult deleteStationGroup(@RequestBody List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new AjaxResult(WamingConstant.FAILURE, "删除失败", "删除失败");
        }
        boolean remove = sysStationGroupService.deleteStationGroup(ids);
        if (remove) {
            //分支机构的设备是否还有授权检查
            sysStationGroupService.checkEquipmentAuth();
            return new AjaxResult(WamingConstant.SUCCESS, "", "删除成功");
        } else {
            return new AjaxResult(WamingConstant.FAILURE, "删除失败", "删除失败");
        }
    }

    /**
     * 修改设备
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据ID查询设备组", notes = "查询ID设备组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "设备组ID", required = true, dataType = "string", paramType = "query")
    })
    @GetMapping(value = "/findStationGroupById")
    public AjaxResult findStationGroupById(@RequestParam("id") String id) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findStationGroupById(id));
    }

    /**
     * 根据设备组查询设备组下的设备
     *
     * @param groupId
     * @param currentPage
     * @param perPage
     * @return
     */
    @ApiOperation(value = "根据设备组查询设备组下的设备", notes = "根据设备组查询设备组下的设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "设备组ID", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "当前第几页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "perPage", value = "每页的数量", dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/findStationGroupEquipments")
    public AjaxResult findStationGroupEquipments(@RequestParam("groupId") String groupId, @RequestParam("currentPage") Integer currentPage, @RequestParam("perPage")
            Integer perPage) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findStationGroupEquipment(groupId, currentPage, perPage));
    }

    /**
     * 查询设备组，用户组，用户
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查询能被授权用户组和用户", notes = "查询能被授权用户组和用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "设备组ID", required = true, dataType = "string", paramType = "query")
    })
    @GetMapping(value = "/findAuthStationGroup")
    public AjaxResult findAuthStationGroup(@RequestParam("id") String id, HttpServletRequest request) {
        boolean isAdmin = CookieUtil.isAdmin(request);
        String userId = CookieUtil.getUserId(request);
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findAuthStationGroup(id, userId, isAdmin));
    }

    @ApiOperation(value = "根据设备组ID查询已经被授权的用户组和用户", notes = "根据设备组ID查询已经被授权的用户组和用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "设备组ID", required = true, dataType = "string", paramType = "query")
    })
    @GetMapping(value = "/findAuthedUsersAndUserGroups")
    public AjaxResult findAuthedUsersAndUserGroups(@RequestParam("id") String groupId) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findAuthedUsersAndUserGroups(groupId));
    }

    @ApiOperation(value = "设备组授权给用户或用户组", notes = "设备组授权给用户或用户组")
    @PostMapping(value = "/authStationGroup")
    public AjaxResult authStationGroup(@RequestBody StationgroupAuthParam stationgroupAuthParam, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        //当前登录用户拥有的监测数据权限设备组编号
        List<String> haveStationgroupIdList = new ArrayList<>();
        if (!StringUtils.isEmpty(stationgroupAuthParam.getOrgId())) {
            haveStationgroupIdList = sysStationGroupService.findStationGroup2AuthUser(stationgroupAuthParam.getOrgId(), userId, CookieUtil.isAdmin(request))
                    .stream().map(SysStationGroup::getId).collect(Collectors.toList());
            //当前登录用户没有权限，直接返回
            if (haveStationgroupIdList.isEmpty()) {
                return new AjaxResult(WamingConstant.FAILURE, "当前登录用户没有可授权的设备组", "当前登录用户没有可授权的设备组");
            }
        }
        return sysStationGroupService.authStationGroup(stationgroupAuthParam, userId, haveStationgroupIdList);
    }

    @ApiOperation(value = "根据用户ID查询已经授权给用户的设备组", notes = "根据用户ID查询已经授权给用户的设备组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "string", paramType = "path"),
    })
    @GetMapping(value = "/findAuthByUserId/{userId}")
    public AjaxResult findAuthStationgroupByUserId(@PathVariable String userId, HttpServletRequest request) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findByUserId(userId));
    }

    @ApiOperation(value = "根据用户组ID查询已经授权给用户的设备组", notes = "根据用户组ID查询已经授权给用户的设备组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "usergroupId", value = "用户组ID", dataType = "string", paramType = "path"),
    })
    @GetMapping(value = "/findAuthByUsergroupId/{usergroupId}")
    public AjaxResult findAuthStationgroupByUsergroupId(@PathVariable String usergroupId, HttpServletRequest request) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findByUsergroupId(usergroupId));
    }

    //模糊查询用户组列表
    @ApiOperation(value = "模糊查询用户组列表", notes = "模糊查询用户组列表")
    @GetMapping(value = "/findLikeUserGroup")
    public AjaxResult findLikeUserGroup(@RequestParam(value = "query", required = false) String query) {
        return new AjaxResult(WamingConstant.FAILURE, "", sysStationGroupService.findLikeUserGroup(query));

    }

    //模糊查询用户组列表
    @ApiOperation(value = "查询用户组下面的用户列表(分页)", notes = "查询用户组下面的用户列表(分页)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "用户组ID", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "当前第几页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "perPage", value = "每页的数量", dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/findUserByUserGroup")
    public AjaxResult findUserByGroup(@RequestParam("groupId") String groupId, @RequestParam("currentPage") Integer currentPage, @RequestParam("perPage") Integer
            perPage) {
        return new AjaxResult(WamingConstant.FAILURE, "", sysStationGroupService.findUserPageByGroup(groupId, currentPage, perPage));

    }

    //模糊查询用户列表
    @ApiOperation(value = "模糊查询用户列表", notes = "模糊查询用户列表")
    @GetMapping(value = "/findLikeUser")
    public AjaxResult findLikeUser(@RequestParam(value = "query", required = false) String query) {
        return new AjaxResult(WamingConstant.FAILURE, "授权失败", sysStationGroupService.findLikeUser(query));
    }

    /*-------------------------------------------Lyh*/
    @ApiOperation(value = "可用设备组API", notes = "上级所属客户设备组")
    @GetMapping(value = "/findStationGroup")
    public AjaxResult findStationGroup(String orgId) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findStationGroup(orgId));
    }

    @ApiOperation(value = "可用设备组API", notes = "上级所属客户设备组", response = SysStationGroup.class)
    @PostMapping(value = "/findEqMgStationGroup")
    public AjaxResult findEqMgStationGroup(@RequestBody OrderIdsAndOrgIdsDTO orderIdsAndOrgIdsDTO, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findEqMgStationGroup(orderIdsAndOrgIdsDTO.getOrderIds(), orderIdsAndOrgIdsDTO
                .getOrgIds(),userId));
    }

    @ApiOperation(value = "已绑定设备组API", notes = "已绑定设备组（sys_order_equipment）API")
    @GetMapping(value = "/findMyStationGroup")
    public AjaxResult findMyStationGroup(String orgId) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findMyStationGroup(orgId));
    }

    @ApiOperation(value = "设备组绑定客户", notes = "设备组绑定客户")
    @PostMapping(value = "/addStationGroupOrg")
    public AjaxResult addStationGroupOrg(@RequestBody SysStationGroupDTO sysStationGroupDTO, HttpServletRequest request) {
        sysStationGroupDTO.setUserId(CookieUtil.getUserId(request));
        AjaxResult ajaxResult = sysStationGroupService.addStationGroupOrg(sysStationGroupDTO);
        if (ajaxResult.getErroCode() == WamingConstant.SUCCESS) {
            //分支机构的设备是否还有授权检查
            sysStationGroupService.checkEquipmentAuth();
        }
        return ajaxResult;
    }

    @ApiOperation(value = "设备组添加设备", notes = "设备组添加设备")
    @PostMapping(value = "/addEquipment")
    public AjaxResult addEquipment(@RequestBody SysStationGroupEquipmentParam eq, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        Map<String, Object> result = sysStationGroupService.addEquipment(eq, userId);
        List<String> res1 = (List<String>) result.get("res1");
        String res2 = result.get("res2").toString();
        if (CollectionUtils.isEmpty(res1) && !StringUtils.isEmpty(res2)) {
            //没有插入，且结果有值，全部已经能绑定
            res2.subSequence(0, res2.length() - 1);
            return new AjaxResult(WamingConstant.PART_SUCCESS, res2 + "设备已经绑定!");
        } else if (CollectionUtils.isEmpty(res1) && StringUtils.isEmpty(res2)) {
            return new AjaxResult(WamingConstant.FAILURE, "添加失败", "");
        } else if (!CollectionUtils.isEmpty(res1) && !StringUtils.isEmpty(res2)) {
            res2.subSequence(0, res2.length() - 1);
            return new AjaxResult(WamingConstant.PART_SUCCESS, "部分添加成功,\" + res2 + \"设备已经绑定!");
        } else {
            return new AjaxResult(WamingConstant.SUCCESS, "", "添加成功");
        }
    }

    /**
     * {
     * "eqId2staionIds": [{'equipmentId':'911911','stationId':'911911'},{'equipmentId':'800800','stationId':'800800'}],
     * "groupId": "a360db516a854321a1129e227fb73999"
     * }
     *
     * @param eq
     * @return
     */
    @ApiOperation(value = "设备组移除设备", notes = "设备组移除设备")
    @PostMapping(value = "/removeEquipment")
    public AjaxResult removeEquipment(@RequestBody SysStationGroupEquipmentParam eq) {
        sysStationGroupService.removeEquipment(eq);
        return new AjaxResult(WamingConstant.SUCCESS, "", "删除成功");
    }

    @ApiOperation(value = "添加设备中的设备组筛选条件", notes = "添加设备中的设备组筛选条件")
    @GetMapping(value = "/findStationGroupByOrgId")
    public AjaxResult findStationGroupByOrgId(@RequestParam("orgId") String orgId) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findStationGroupByOrgId(orgId));
    }

    @ApiOperation(value = "设备组授权给用户或用户组时需要查询的设备组列表", notes = "设备组授权给用户或用户组时需要查询的设备组列表")
    @GetMapping(value = "/findStationGroup2AuthUser")
    public AjaxResult findStationGroup2AuthUser(@RequestParam("orgId") String orgId, HttpServletRequest request) {
        boolean isAdmin = CookieUtil.isAdmin(request);
        String userId = CookieUtil.getUserId(request);
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findStationGroup2AuthUser(orgId, userId, isAdmin));
    }

    @ApiOperation(value = "设备管理权限授权给用户时可用设备组列表", notes = "设备管理权限授权给用户时可用设备组列表",
            response = SysStationGroup.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "用户所属组织ID", dataType = "string", paramType = "query"),
    })
    @GetMapping(value = "/findAuthStationgroupManage")
    public AjaxResult findAuthStationgroupManage(@RequestParam("orgId") String orgId, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        Boolean isAdmin = CookieUtil.isAdmin(request);
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findAuthStationgroupManage(orgId, userId, isAdmin));
    }

    @ApiOperation(value = "设备管理权限授权给用户", notes = "设备管理权限授权给用户")
    @GetMapping(value = "/authStationManage")
    public AjaxResult authStationManage(@RequestBody StationgroupAuthParam stationgroupAuthParam, HttpServletRequest request) {
        String userId = CookieUtil.getUserId(request);
        sysStationGroupService.authStationManage(stationgroupAuthParam, userId);
        return new AjaxResult(WamingConstant.SUCCESS, "", "");
    }

    @ApiOperation(value = "查询设备", notes = "查询设备", response = SysEquipmentDTO.class)
    @PostMapping(value = "/findEquipment")
    public AjaxResult findEquipment(@RequestBody StationGroupEquipmentBO stationGroupEquipmentBO) {
        return new AjaxResult(WamingConstant.SUCCESS, "", sysStationGroupService.findStationGroupEquipmentList(stationGroupEquipmentBO));
    }
}


